import java.util.Comparator;
import java.util.PriorityQueue;

/**
 * Created with IntelliJ IDEA
 * Description 优先级队列测试
 * User: 王杰
 * Date: 2025-06-06
 * Time: 20:11
 */
// 控制大根堆/小根堆
class Intcmp implements Comparator<Integer> {
    @Override
    public int compare(Integer o1, Integer o2) {
        return o2.compareTo(o1);
    }
}
public class PriorityQueueTest {
//    public int[] smallestK(int[] arr, int k) {
//        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(k, new Intcmp());
//
//        // K * logK
//        for (int i = 0; i < k; i++) {
//            priorityQueue.offer(arr[k]);
//        }
//
//        // (N - K) * logK
//        for (int i = k; i < arr.length; i++) {
//            int peekVal = priorityQueue.peek();
//            if (arr[i] < peekVal) {
//                priorityQueue.poll();
//                priorityQueue.offer(peekVal);
//            }
//        }
//
//        int[] ret = new int[k];
//        for (int i = 0; i < k; i++) {
//            ret[i] = priorityQueue.poll();
//        }
//        return ret;
//    }

    // 找数据中最小k个值
    public int[] smallestK(int[] arr, int k) {
        int[] ret = new int[k];
        if(arr == null || k ==0) {
            return ret;
        }

        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(new Intcmp());

        // K * logK
        for (int i = 0; i < k; i++) {
            priorityQueue.offer(arr[i]);
        }

        // (N - K) * logK
        for (int i = k; i < arr.length; i++) {
            int peekVal = priorityQueue.peek();
            if (arr[i] < peekVal) {
                priorityQueue.poll();
                priorityQueue.offer(arr[i]);
            }
        }

        for (int i = 0; i < k; i++) {
            ret[i] = priorityQueue.poll();
        }
        return ret;
    }

    public static void main(String[] args) {
        PriorityQueueTest priorityQueueTest = new PriorityQueueTest();
        int[] arr = {1,3,5,7,2,4,6,8};
        int k = 4;
        priorityQueueTest.smallestK(arr, k);
    }
    public static void main1(String[] args) {
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(new Intcmp());

        priorityQueue.offer(10);
        priorityQueue.offer(20);
        priorityQueue.offer(3);

        System.out.println(priorityQueue.peek());// 3 小根堆

    }
}
